from django.shortcuts import render,redirect
from detail import models
from django.http import JsonResponse
# Create your views here.

def detailList(request):
    """展示成绩的列表"""
    # 从数据库中取出所有学数据
    gradeData = models.GradeDetail.objects.all()
    return render(request, 'grade_detail.html', {'gradeData':gradeData})


from django import forms

class detailtModelform(forms.ModelForm):
    class Meta:
        model = models.GradeDetail
        fields=['id','sno','sname','math','english','Clanguage','JavaGrade','PythonGrade','DataStruct']

def student_add(request):

    if request.method == "GET":
        form = detailtModelform()
        return render(request, 'add_student.html',{"form" : form})
    # 用户通过POST提交数据，数据校验。
    form = detailtModelform(data=request.POST)
    #如果数据合法，保存到数据库
    if form.is_valid():
        form.save()
        return render(request,'grade_detail.html')
    # 校验失败
    else:
        return render(request, 'add_student.html', {"form" : form})


def student_delete(request, nid):
    """删除学生记录"""
    models.GradeDetail.objects.filter(id=nid).delete()
    return redirect('/gradeDetail/')


def student_edit(request, nid):
    """编辑学生"""
    # 如果是GET请求
    if request.method == 'GET':
        # 根据ID去数据库获取要编辑的哪一行id
        row_object = models.GradeDetail.objects.filter(id=nid).first()
        # 使用form 显示编辑的列 ，并用intance 匹配
        form = detailtModelform(instance=row_object)
        return render(request,'edit.html',{'form':form})
    # 如果是post请求
    row_object = models.GradeDetail.objects.filter(id=nid).first()
    form = detailtModelform(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/gradeDetail/')
    return render(request, 'edit.html',{"form":form})


from django.core.paginator import Paginator
import random

def randomName(request):
    """
    随机生成一个名字
    """
    # 获取所有对象
    all = models.GradeDetail.objects.all()
    page = Paginator(all, 1)
    count = page.count
    # 随机获取一个对象
    rand = random.randint(1, count)
    Sname = models.GradeDetail.objects.filter(id=rand).get()
    return JsonResponse({'name': Sname.sname })


def sort(request):
   stu = {}
   if request.POST:
      proj = request.POST.get("proj")
      if proj == '1':
         stulist = models.GradeDetail.objects.order_by("-math")
         stu = {"stulist": stulist, "proj": proj, }
      elif proj == '2':
         stulist = models.GradeDetail.objects.order_by("-english")
         stu = {"stulist": stulist, "proj": proj, }
      elif proj == '3':
         stulist = models.GradeDetail.objects.order_by("-Clanguage")
         stu = {"stulist": stulist, "proj": proj, }
      elif proj == '4':
         stulist = models.GradeDetail.objects.order_by("-JavaGrade")
         stu = {"stulist": stulist, "proj": proj, }
      elif proj == '5':
         stulist = models.GradeDetail.objects.order_by("-PythonGrade")
         stu = {"stulist": stulist, "proj": proj, }
      elif proj == '6':
         stulist = models.GradeDetail.objects.order_by("-DataStruct")
         stu = {"stulist":stulist,"proj":proj, }
   return render(request, "sort.html", stu)


from django.http import StreamingHttpResponse

def download(request):
    def file_iterator(file_name, chunk_size=512):#用于形成二进制数据
        with open(file_name,'rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break
    the_file_name ="F:\\Sams\\static\\excelFile\\grade_detail.csv"#要下载的文件路径
    response =StreamingHttpResponse(file_iterator(the_file_name))#这里创建返回
    response['Content-Type'] = 'application/vnd.ms-excel'#注意格式
    response['Content-Disposition'] = 'attachment;filename="grade.csv"'#注意filename 这个是下载后的名字
    return response


def dbschart(request):
    # 先读出GradeDetail表的对象信息，读出所有数据
    # 一行数据就是一个对象
    objs = models.GradeDetail.objects.all()
    # locals 函数可以将改函数中的所有变量传入到展示页面中
    return render(request, 'dbschart.html',locals())



